from django import template
from django import forms
from django.http import HttpResponseRedirect

from pirateissues.models import Topic
from native_tags.decorators import block
from genericview.views import HttpRedirectException, namespace_get

get_namespace = namespace_get('pp_topic')

@block
def pp_get_topic_list(context, nodelist, *args, **kwargs):
    """
    This block tag will grab a list of topics. In the future, the list might
    also be optionally generated as per a specific user.

    In order to generate a url that will provide rng information to this tag via
    request.range, use a url tag of the following form:

    {% url pp-page template="filename.html" start=0 end=20 %}

    In this way, the tag can be invoked as follows:

    {% pp_get_topic_list range=request.range %}
       Do stuff with {{ pp_topic.topic_list }}
    {% endpp_get_topic_list %}
    """
    
    context.push()
    namespace = get_namespace(context)
    
    rng = kwargs.pop('range',None)
    
    if isinstance(rng, basestring):
        try:
            rng = rng.strip("()").split(",")
            rng = (int(rng[0]), int(rng[1]))
        except:
            rng = None
            
    if rng != None and len(rng) != 2:
        raise ValueError("The argument 'range='"+ str(rng) + "  to the pp_topic_list tag "
                         "must be provided either in the form of an (int, int) pair, or "
                         "as a string in the form of '(<int>, <int>)'.")

    topic_list = Topic.objects.all()
    if rng:
        topic_list = topic_list[rng[0]:rng[1]]

    namespace['topic_list'] = topic_list
    output = nodelist.render(context)
    context.pop()

    return output
    
@block
def pp_topic_form(context, nodelist, *args, **kwargs):
    '''
    This block tag can create or process forms eitfrom genericview.views import HttpRedirectException, namespace_gether to create or to modify arguments.
    Usage is as follows:

    {% pp_topic_form POST=request.POST path=request.path topic=pp_topic.topic%}
       Do stuff with {{ pp_topic.form }}.
    {% endpp_topic_form %}
    '''
    context.push()
    namespace = get_namespace(context)

    POST  = kwargs.get('POST', None)
    path  = kwargs.get('path', "")
    topic = kwargs.get('topic',None)

    if POST and POST.get("form_id") == "pp_topic_form":
        form = TopicForm(POST) if topic is None else TopicForm(POST, instance=topic)
        if form.is_valid():
            new_issue = form.save()
            raise HttpRedirectException(HttpResponseRedirect(path))
    else:
        form = TopicForm() if topic is None else TopicForm(instance=topic)

    namespace['form'] = form
    output = nodelist.render(context)
    context.pop()

    return output     
    
class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="pp_topic_form")

